﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Text.RegularExpressions;

namespace AuroraWuBi
{
    //词组类
   public class Phrase
    {
        private Dictionary<string, string> _PhraseDit;//所有编码

        public Dictionary<string, string> PhraseDit
        {
            get
            {
                return _PhraseDit;
            }
        }

        //public void AddPhrase(string _phrase, Dictionary<string, string> _AddWordMakingCode)
        //{
        //    string _code = setPhraseCode(_phrase, _AddWordMakingCode);
        //    if (_code == null)
        //        return;

        //}

        public string setPhraseCode(string _phrase, Dictionary<string, string> _AddWordMakingCode)
        {
            string _code = "";

            string line = _phrase.Trim();
            Regex spaceRegex = new Regex("[a-zA-Z]");
            Regex regex = new Regex("^#.*|name:.*|^version:.*|^sort:.*|^use_preset_vocabulary:.*|^columns:.*|-.*|^import_tables:.*|^encoder:.*|^exclude_patterns:.*|^rules:.*|^formula:.*");//^[\u4e00-\u9fa5].*

            Regex punctuationRegex = new Regex(":|：|？|\\?|[\u0021-\u002f\u003a-\u0040\u005b-\u0060\u007b-\u008f\u00a0-\u00bf\u00d7\u00f7\u2000-\u2bff\u3000-\u303f\u30a0\u30fb]");

            if (punctuationRegex.IsMatch(line) | spaceRegex.IsMatch(line))
            {
                
                Console.WriteLine("警告：词语：{0}，含有非中文，已忽略", _phrase);
                return null;
            }

            //if (punctuationRegex.IsMatch(line))
            //{
            //    line = punctuationRegex.Replace(line, "");
            //    Console.WriteLine("警告：词语：{0}，含有特殊符号，已自动去除特殊符号", _phrase);
            //}

            line = TranslateChineseNumber(line);

            if (line.Length > 1)
            {

                if (line.StartsWith(".") | regex.IsMatch(line))
                {
                    Console.WriteLine("警告：已忽略词语：{0}，因为无法自动生成编码", _phrase);
                }
                else 
                {
                    string word1 = line.Trim().Substring(0, 1).Trim();
                    string word2 = line.Trim().Substring(1, 1).Trim();
                    string c = "";
                    if (line.Length == 2)
                    {
                        if (!_AddWordMakingCode.ContainsKey(word1))
                        {
                            Console.WriteLine("无法生成词语【{0}】的编码，因为不存在单字【{1}】的编码", _phrase, word1);
                            return null;
                        }

                        string c1 = _AddWordMakingCode[word1];

                        string c2;
                        if (spaceRegex.IsMatch(word2))
                        {
                            c2 = word2.ToLower();
                            Console.WriteLine("警告：词语：{0}，含有英文字母，直接取字母为编码", _phrase);
                        }
                        else
                        {
                            if (!_AddWordMakingCode.ContainsKey(word2))
                            {
                                Console.WriteLine("无法生成词语【{0}】的编码，因为不存在单字【{1}】的编码", _phrase, word2);
                                return null;
                            }
                            c2 = _AddWordMakingCode[word2];
                        }


                        
                        c = c1 + c2;
                    }
                    else if (line.Length == 3)
                    {
                        string c3;
                        string word3 = line.Substring(2, 1);
                        if (spaceRegex.IsMatch(word3))
                        {
                            c3 = word3.ToLower();
                            Console.WriteLine("警告：词语：{0}，含有英文字母，直接取字母为编码", _phrase);
                        }
                        else
                        {
                            if (!_AddWordMakingCode.ContainsKey(word3))
                            {
                                Console.WriteLine("无法生成词语【{0}】的编码，因为不存在单字【{1}】的编码", _phrase, word3);
                                return null;
                            }
                            c3 = _AddWordMakingCode[word3].Substring(0, 1);
                        }
                        string c1 = _AddWordMakingCode[word1].Substring(0, 2);
                        string c2 = _AddWordMakingCode[word2].Substring(0, 1);
                         
                        c = c1 + c2 + c3;
                    }
                    else
                    {
                        string word3 = line.Substring(2, 1);
                        string wordn = line.Substring(line.Length - 1);
                        string c3, cn;
                        if (spaceRegex.IsMatch(word3))
                        {
                            c3 = word3.ToLower();
                            Console.WriteLine("警告：词语：{0}，含有英文字母，直接取字母为编码", _phrase);
                        }
                        else
                        {
                            if (!_AddWordMakingCode.ContainsKey(word3))
                            {
                                Console.WriteLine("无法生成词语【{0}】的编码，因为不存在单字【{1}】的编码", _phrase, word3);
                                return null;
                            }
                            c3 = _AddWordMakingCode[word3].Substring(0, 1);
                        }

                        if (spaceRegex.IsMatch(wordn))
                        {
                            cn = wordn.ToLower();
                            Console.WriteLine("警告：词语：{0}，含有英文字母，直接取字母为编码", _phrase);
                        }
                        else
                        {
                            if (!_AddWordMakingCode.ContainsKey(wordn))
                            {
                                Console.WriteLine("无法生成词语【{0}】的编码，因为不存在单字【{1}】的编码", _phrase, wordn);
                                return null;
                            }
                            c3 = _AddWordMakingCode[word3].Substring(0, 1);
                            cn = _AddWordMakingCode[wordn].Substring(0, 1);
                        }
                        string c1 = _AddWordMakingCode[word1].Substring(0, 1);
                        string c2 = _AddWordMakingCode[word2].Substring(0, 1);
                        
                        
                        c = c1 + c2 + c3 + cn;
                    }
                    _code = c;
                }
            }
            if (string.IsNullOrEmpty(_code))
                return null;
            else
            {
                if (_PhraseDit == null)
                {
                    _PhraseDit = new Dictionary<string, string>();
                    _PhraseDit.Add(_phrase, _code);
                }
                else
                {
                    if (_PhraseDit.ContainsKey(_phrase))
                    {
                        if (!_PhraseDit[_phrase].Contains(_code))
                            _PhraseDit.Add(_phrase, _code);
                    }
                    else
                    {
                        _PhraseDit.Add(_phrase, _code);
                    }
                }
                return _code;
            }
                

        }



        /// 把字符串中的数字转换为汉字. 当数字不以0开头，并且以多个0结尾时，按照x千x百的方式转换。否则直接读挨个数字。
        private String TranslateChineseNumber(String str)
        {
            StringBuilder builder = new StringBuilder();
            StringBuilder buffer = new StringBuilder();

            foreach (Char c in str)
            {
                if (c <= '9' && c >= '0')
                {
                    buffer.Append(c);
                }
                else
                {
                    if (buffer.Length > 0)
                    {
                        builder.Append(Num2Chs(buffer.ToString()));
                        buffer = new StringBuilder();
                    }
                    builder.Append(c);
                }
            }

            if (buffer.Length > 0)
            {
                builder.Append(Num2Chs(buffer.ToString()));
                Console.WriteLine("警告：词语：{0}，含有数字，已自动成换成中文", str);
            }
                

           
            return builder.ToString();
        }
        private String Num2Chs(String str)
        {
            Regex regex = new Regex("[1-9].+(0{2,100})");
            if (regex.IsMatch(str))
                return Int2Chs(long.Parse(str));

            Char[] chars = new Char[str.Length];

            for (int i = 0; i < str.Length; i++)
            {
                chars[i] = Num2Char(str[i]);
            }

            return new String(chars);

        }
        private char Num2Char(Char c)
        {
            switch (c)
            {
                case '1':
                    return '一';
                case '2':
                    return '二';
                case '3':
                    return '三';
                case '4':
                    return '四';
                case '5':
                    return '五';
                case '6':
                    return '六';
                case '7':
                    return '七';
                case '8':
                    return '八';
                case '9':
                    return '九';
            }
            return '零';
        }


        // 十位以上的数字转换汉字, 来自这里 https://blog.csdn.net/iplayvs2008/article/details/89517321
        private static string Int2Chs(long input)
        {
            string ret = null;
            long input2 = Math.Abs(input);
            string resource = "零一二三四五六七八九";
            string unit = "个十百千万亿兆京垓秭穰沟涧正载极";
            if (input > Math.Pow(10, 4 * (unit.Length - unit.IndexOf('万'))))
            {
                throw new Exception("the input is too big,input:" + input);
            }
            Func<long, List<List<int>>> splitNumFunc = (val) =>
            {
                int i = 0;
                int mod;
                long val_ = val;
                List<List<int>> splits = new List<List<int>>();
                List<int> splitNums;
                do
                {
                    mod = (int)(val_ % 10);
                    val_ /= 10;
                    if (i % 4 == 0)
                    {
                        splitNums = new List<int>();
                        splitNums.Add(mod);
                        if (splits.Count == 0)
                        {
                            splits.Add(splitNums);
                        }
                        else
                        {
                            splits.Insert(0, splitNums);
                        }
                    }
                    else
                    {
                        splitNums = splits[0];
                        splitNums.Insert(0, mod);
                    }
                    i++;
                } while (val_ > 0);
                return splits;
            };
            Func<List<List<int>>, string> hommizationFunc = (data) =>
            {
                List<StringBuilder> builders = new List<StringBuilder>();
                for (int i = 0; i < data.Count; i++)
                {
                    List<int> data2 = data[i];
                    StringBuilder newVal = new StringBuilder();
                    for (int j = 0; j < data2.Count;)
                    {
                        if (data2[j] == 0)
                        {
                            int k = j + 1;
                            for (; k < data2.Count && data2[k] == 0; k++) ;
                            //个位不是0，前面补一个零
                            newVal.Append('零');
                            j = k;
                        }
                        else
                        {
                            newVal.Append(resource[data2[j]]).Append(unit[data2.Count - 1 - j]);
                            j++;
                        }
                    }
                    if (newVal[newVal.Length - 1] == '零' && newVal.Length > 1)
                    {
                        newVal.Remove(newVal.Length - 1, 1);
                    }
                    else if (newVal[newVal.Length - 1] == '个')
                    {
                        newVal.Remove(newVal.Length - 1, 1);
                    }

                    if (i == 0 && newVal.Length > 1 && newVal[0] == '一' && newVal[1] == '十')
                    {//一十 --> 十
                        newVal.Remove(0, 1);
                    }
                    builders.Add(newVal);
                }
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < builders.Count; i++)
                {//拼接
                    if (builders.Count == 1)
                    {//个位数
                        sb.Append(builders[i]);
                    }
                    else
                    {
                        if (i == builders.Count - 1)
                        {//万位以下的
                            if (builders[i][builders[i].Length - 1] != '零')
                            {//十位以上的不拼接"零"
                                sb.Append(builders[i]);
                            }
                        }
                        else
                        {//万位以上的
                            if (builders[i][0] != '零')
                            {//零万零亿之类的不拼接
                                sb.Append(builders[i]).Append(unit[unit.IndexOf('千') + builders.Count - 1 - i]);
                            }
                        }
                    }
                }
                return sb.ToString();
            };
            List<List<int>> ret_split = splitNumFunc(input2);
            ret = hommizationFunc(ret_split);
            if (input < 0) ret = "-" + ret;
            return ret;
        }

    }
}
